import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/store/store_detail_page.dart';
import 'package:gzmall_app/model/store.dart';

class NearStoreListPage extends StatefulWidget {
  String latitude = "", longitude = "", adcode = "";
  String params = "";

  NearStoreListPage({this.latitude, this.longitude, this.adcode, this.params});

  @override
  State<StatefulWidget> createState() => NearStoreListPageState(
      latitude: latitude, longitude: longitude, params: params);
}

class NearStoreListPageState extends State<NearStoreListPage> {
  String latitude = "", longitude = "", adcode = "";
  String params = "";

  List<Store> _storeList = [];

  int _curPage = 1;
  RefreshListView _refreshListView;
  bool _showEmpty = false;

  NearStoreListPageState(
      {this.latitude, this.longitude, this.adcode, this.params});

  @override
  void initState() {
    super.initState();
    _getShopsNear(latitude, longitude, adcode, 1);
  }

  @override
  Widget build(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: ListView.builder(
        itemCount: _storeList.length,
        itemBuilder: (BuildContext context, int index) {
          Store _store = _storeList[index];
          double _width =
              (MediaQuery.of(context).size.width - (10 * 4) - (2 * 10)) / 3;
          double _topMargin = index == 0 ? 10.0 : 0.0;

          List<Widget> _products = [];
          if (_store.spus != null && _store.spus.length > 0) {
            List<Widget> items = _store.spus.map((item) {
              return CachedNetworkImage(
                height: _width,
                width: _width,
                imageUrl: item.avatar,
                fit: BoxFit.fill,
                errorWidget: (BuildContext context, String url, Object error) {
                  return Container(
                    color: Colors.grey,
                    width: _width,
                    height: _width,
                  );
                },
              );
            }).toList();
            for (var i = 0; i < items.length; i++) {
              if (i < 3) {
                _products.add((i == 1
                    ? Container(
                        margin: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: items[i])
                    : items[i]));
              } else {
                break;
              }
            }
          } else {
            _products.add(Container());
          }

          return InkWell(
              onTap: () {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new StoreDetailPage(store: _store);
                }));
              },
              child: Container(
                  color: Colors.white,
                  margin: EdgeInsets.only(
                    left: 10.0,
                    right: 10.0,
                    bottom: 10.0,
                    top: _topMargin,
                  ),
                  padding: const EdgeInsets.all(10.0),
                  child: Column(children: <Widget>[
                    Row(children: <Widget>[
                      CachedNetworkImage(
                        height: 40.0,
                        width: 40.0,
                        imageUrl: _store.avatar,
                        fit: BoxFit.fill,
                        errorWidget:
                            (BuildContext context, String url, Object error) {
                          return Container(
                            color: Colors.grey,
                            width: _width,
                            height: _width,
                          );
                        },
                      ),
                      Expanded(
                        child: Padding(
                          padding:
                              const EdgeInsets.only(left: 10.0, right: 10.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(_store.name),
                              Text(
                                '${_store.distance} 公里',
                                style: TextStyle(fontSize: 10),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Text(
                        "进店",
                        style: TextStyle(color: ColorCommon.primaryColor),
                      ),
                    ]),
                    Container(
                      margin: const EdgeInsets.only(top: 10.0, bottom: 10.0),
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: _products),
                    ),
                  ])));
        },
      ),
      showEmpty: _showEmpty,
      onReload: () {
        _getShopsNear(latitude, longitude, adcode, 1);
      },
    );
    return Scaffold(appBar: _createAppBar(), body: _refreshListView);
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("附近门店"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getShopsNear(latitude, longitude, adcode, 1);
    } else {
      _getShopsNear(latitude, longitude, adcode, _curPage + 1);
    }
  }

  _getShopsNear(String latitude, String longitude, String adcode, int page) {
    bool isGetNew = page == 1;
    Map<String, Object> params = {
      "latitude": latitude,
      "longitude": longitude,
      "adcode": adcode,
      "page": page.toString()
    };
    if (this.params != null && this.params.isNotEmpty) {
      Map<String, dynamic> otherParams = json.decode(this.params);
      params.addAll(otherParams);
    }

    NetUtil.get(
        context,
        Api.shopsNear,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Store.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            if (isGetNew) {
              _storeList = _dataList;
            } else {
              _storeList.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty =
                isGetNew && (_storeList == null || _storeList.length <= 0);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }
}
